/**
 * 客户端公共JS
 */

    window.subcmd = {};
   // window.subcmd['ping'] = ping;
   window.subcmd['login'] = onLogin;
   window.subcmd['logout'] = onLogout;
   window.subcmd['msg'] = onMsg;
   window.subcmd['msg_1'] = onMsgGroup;
   window.subcmd['msg_2'] = onMsgTo;
   window.subcmd['speak'] = onSpeak;
   window.subcmd['gift'] = onGift;
   window.subcmd['kick'] = onKick;
   window.subcmd['error'] = onError;
   window.subcmd['userList'] = onUserList;
   window.subcmd['ad'] = onAd;

    /********************************消息包 START**************************************/

    //心跳包
    function ClientPing() {
        this.cmd = 'ping';
    }

    //全站公告包
    function ClientAd() {
        this.cmd = 'ad';
        this.msg = ' ';
        this.data = ' ';
    }

    //普通消息包
    function ClientMsg() {
        this.cmd = 'msg';
        this.srcClientId = 0;
        this.toClientId = 0;
        this.userId = 0;
        this.room = room;
        this.group = group;
        this.msg = '';
        this.toMsg = ' ';
        this.data = '';
        this.type = 0;//0广播、1组播、2互播
    }

   //禁言消息包
   function ClientForbiddenSpeak() {
       this.cmd = 'speak';
       this.srcClientId = 0;
       this.toClientId = 0;
       this.room = 1;
       this.notAllowUserId = 0;
       this.group = group;
       this.msg = ' ';
       this.time = '';//禁言时长[秒]
       this.data = 1;//1禁言，0解除
   }

   //送礼消息包
   function ClientSendGift() {
       this.cmd = 'gift';
       this.srcClientId = 0;
       this.toClientId = 0;
       this.room = room;
       this.userId = 0;
       this.group = group;
       this.msg = ' ';
       this.data = '';
       this.number = 1;
   }

   //踢出消息包
   function ClientKick() {
       this.cmd = 'kick';
       this.srcClientId = 0;
       this.toClientId = 0;
       this.room = room;
       this.userId = 0;
       this.group = group;
       this.msg = ' ';
       this.data = '';
   }

    //客户端用户登录包
    function ClientLogin() {
        this.cmd = 'login';
        this.type = 1;//0为游客，1为用户
        this.userId = 0;
        this.room = room;
        this.group = group;
    }

   //客户端用户列表包
   function ClientUserList() {
       this.cmd = 'userList';
       this.clientId = ' ';
   }

    /********************************消息包 END**************************************/


   /********************************webSoeket START**************************************/
        //连接服务端
    var setping;
    var ws;
    // var userId = 1;
    // var room = 1;
    // var group = 1;

    function connect() {
        var wsServer = 'ws://120.79.209.186:9501';
        ws = new WebSocket(wsServer);
        ws.onopen = onopen;
        ws.onmessage = onmessage;
        ws.onclose = onclose;
        ws.onerror = onerror;
    }

    //连接到服务器
    function onopen(evt) {
        //设置定时发送心跳包
        setping = setInterval("sendClientPing()", 3000);

        //设置登录用户
        var clientUser = new ClientLogin();
        clientUser.type = 0;
        clientUser.userId = userId;
        clientUser.room = room;
        clientUser.group = group;
        ws.send(JSON.stringify(clientUser));

        $('#userlist').empty();
    }

    // 服务端发来消息时
    function onmessage(evt) {
        var data = JSON.parse(evt.data);
        //返回解析后的数据
        if(isJsonFormat(data['data'])){
            data['data'] = JSON.parse(data['data']);
        }
        console.log('收到：');
        console.log(data);
        // if(data.code == 205){//被禁言
        //     alert(data.msg);
        //     window.close();
        // }
        //执行相应函数
        try {
            if(data['data']['type'] != undefined && data['data']['type'] > 0){
                window.subcmd[data['data']['cmd'] + '_' + data['data']['type']](data['data']);
            }else{
                window.subcmd[data['data']['cmd']](data['data']);
            }
        }catch (e) {
            console.log(e);
            window.subcmd['error'](data['data']);
        }
    }

    // 连接关闭
    function onclose(evt) {
        //console.log("连接关闭，定时重连");
        clearInterval(setping);
        setTimeout(function () {
            connect();
        }, 3000);
    }

    //连接错误
    function onerror(evt) {
        console.log('Error occured: ' + evt.data);
    }

    //发送心跳包
    function sendClientPing() {
        var clientPing = new ClientPing();
        ws.send(JSON.stringify(clientPing));
    }

    //是否json格式
    function isJsonFormat( str ) {
        try {
            JSON.parse(str);
        } catch (e) {
            return false;
        }
        return true;
    }

    function getUserList() {
    //     //初次加载用户列表
    //     var userList = new ClientUserList();
    //     userList.cmd = 'userList';
    //     userList.clientId = srcClientId;
    //     ws.send(JSON.stringify(userList));
    }

   /********************************webSoeket END**************************************/


   /********************************辅助函数 START**************************************/

   /**
    *
    * 获取当前时间
    */
   function getNow(){
       function p(s) {
           return s < 10 ? '0' + s: s;
       }

       var myDate = new Date();
       //获取当前年
       var year=myDate.getFullYear();
       //获取当前月
       var month=myDate.getMonth()+1;
       //获取当前日
       var date=myDate.getDate();
       var h=myDate.getHours();       //获取当前小时数(0-23)
       var m=myDate.getMinutes();     //获取当前分钟数(0-59)
       var s=myDate.getSeconds();

       var now = year+'-'+p(month)+"-"+p(date)+" "+p(h)+':'+p(m)+":"+p(s);

       return now;
   }

   /**
    * 关闭当前页面（当前页面必须是脚本打开的才行）
    */
   function closeWindows() {
       var userAgent = navigator.userAgent;
       if (userAgent.indexOf("Firefox") != -1
           || userAgent.indexOf("Chrome") != -1) {
           close();//直接调用JQUERY close方法关闭
       } else {
           window.opener = null;
           window.open("", "_self");
           window.close();
       }
   };

   /********************************辅助函数 END**************************************/
